import React, { useState } from 'react';
import { NavBar, Card, Rate, TextArea, Button, Toast, Tag } from 'antd-mobile';
import { Uploader } from 'react-vant';
import { useNavigate, useLocation } from 'react-router-dom';
import './Com/Remark.css';

// 订单数据类型
interface Order {
  orderId: string;
  productName: string;
  price: number;
  quantity: number;
  status: string;
  orderTime: string;
  paymentMethod: string;
  deliveryAddress: string;
  pickupCode?: string;
}

// 文件类型
interface FileItem {
  file?: File;
  url?: string;
  status?: 'uploading' | 'done' | 'error';
  uid?: string;
}

const Remark: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const orderData = location.state?.order as Order;
  
  const [rating, setRating] = useState<number>(3);
  const [content, setContent] = useState<string>('');
  const [fileList, setFileList] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(false);

  const handleBack = (): void => {
    navigate(-1);
  };

  // 处理文件上传
  const handleUpload = (files: FileItem[]) => {
    // 验证文件
    const validFiles = files.filter(item => {
      if (item.file) {
        const isImage = item.file.type.startsWith('image/');
        const isLt2M = item.file.size / 1024 / 1024 < 2;
        
        if (!isImage) {
          Toast.show('只能上传图片格式的文件！');
          return false;
        }
        if (!isLt2M) {
          Toast.show('图片大小不能超过2MB！');
          return false;
        }
        return true;
      }
      return true;
    });
    
    setFileList(validFiles);
  };

  // 提交评论
  const handleSubmit = async () => {
    if (!orderData) {
      Toast.show('订单信息不存在');
      return;
    }

    if (!content.trim()) {
      Toast.show('请输入评论内容');
      return;
    }

    try {
      setLoading(true);
      
      // 获取用户ID
      const yonghuId = localStorage.getItem('yonghuId');
      if (!yonghuId) {
        Toast.show('请先登录');
        return;
      }

      // 处理图片数据
      const imageUrls = fileList.map(item => item.url).filter(url => url);

      const commentData = {
        orderId: orderData.orderId,
        rating,
        content: content.trim(),
        images: imageUrls,
        createTime: new Date().toISOString(),
        userId: yonghuId,
        userName: '用户' // 可以从用户信息获取
      };

      // 这里可以调用API保存评论
      console.log('提交评论:', commentData);
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      Toast.show('评论提交成功！');
      
      // 返回订单页面
      navigate('/my/order', { replace: true });
      
    } catch (error) {
      console.error('提交评论失败:', error);
      Toast.show('提交失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 如果没有订单数据，显示错误
  if (!orderData) {
    return (
      <div className="remark-page">
        <NavBar onBack={handleBack}>
          商品评价
        </NavBar>
        <div className="error-message">
          <p>订单信息不存在</p>
          <Button onClick={handleBack}>返回</Button>
        </div>
      </div>
    );
  }

  return (
    <div className="remark-page">
      <NavBar onBack={handleBack}>
        商品评价
      </NavBar>

      {/* 订单信息 */}
      <Card className="order-info-card">
        <div className="order-info">
          <div className="product-info">
            <h3>{orderData.productName}</h3>
            <p>订单号: {orderData.orderId}</p>
            <p>价格: ¥{orderData.price.toFixed(2)} × {orderData.quantity}</p>
          </div>
          <Tag color="success">已完成</Tag>
        </div>
      </Card>

      {/* 评分区域 */}
      <Card className="rating-card">
        <div className="rating-section">
          <div className="rating-title">
            <span>商品评分</span>
            <span className="rating-text">
              {rating === 5 ? '非常满意' : 
               rating === 4 ? '满意' : 
               rating === 3 ? '一般' : 
               rating === 2 ? '不满意' : '很不满意'}
            </span>
          </div>
          <Rate
            value={rating}
            onChange={(value) => {
              console.log('评分：', value);
              setRating(value);
            }}
            allowHalf={false}
          />
        </div>
      </Card>

      {/* 评论内容 */}
      <Card className="comment-card">
        <div className="comment-section">
          <div className="comment-title">评论内容</div>
          <TextArea
            value={content}
            onChange={setContent}
            placeholder="分享您的使用体验吧..."
            rows={4}
            maxLength={500}
            showCount
            className="comment-textarea"
          />
        </div>
      </Card>

      {/* 图片上传 */}
      <Card className="image-card">
        <div className="image-section">
          <div className="image-title">上传图片 (最多5张)</div>
          <Uploader
            value={fileList}
            onChange={handleUpload}
            multiple
            maxCount={5}
            className="image-uploader"
            accept="image/*"
          />
        </div>
      </Card>

      {/* 提交按钮 */}
      <div className="submit-section">
        <Button
          color="primary"
          size="large"
          onClick={handleSubmit}
          loading={loading}
          className="submit-button"
        >
          提交评价
        </Button>
      </div>
    </div>
  );
};

export default Remark;
